<template>
  <div>
    <el-tab-pane v-for="item in dataStruct" :key="item.tabValue" :label="`${item.tabKey} ${item.tabTitle}`" :name="item.tabValue">
      <template #label>
        <span @click="tabPanelClick(item)">{{ `${item.tabKey} ${item.tabTitle}` }}</span>
      </template>
      <div class="padding-lr-xs">
        <vxe-form :ref="`formRef${item.tabKey}`" :data="formData">
          <vxe-form-item class="padding-lr-xs" :align="formItm.align" :title="formItm.title" :field="formItm.field" :title-width="formItm.titleWidth" :title-colon="formItm.titleColon === 1" :title-asterisk="formItm.titleAsterisk === 1" :title-overflow="formItm.titleOverflow === 1" :show-title="formItm.showTitle === 1" :title-align="formItm.titleAlign" :vertical="formItm.vertical === 1" :content-class-name="formItm.contentClassName" :visible="formItm.visible === 1" :span="formItm.span" v-for="(formItm, formIdx) in item.formObj.formItems" :key="formIdx">
            <template #title>
              <div @click="formItemCLick(formItm, formIdx, null)">
                <span class="padding-left-xs">{{ `${formItm.fieldCode} ${formItm.title}` }}</span>
              </div>
            </template>
            <template #default="params">
              <div @click="formItemCLick(formItm, formIdx, params)">
                <vxe-input v-if="formItm.compType === 'input'" v-model="params.data[formItm.field]" placeholder="请输入" clearable></vxe-input>

                <vxe-input v-if="formItm.compType === 'date' || formItm.compType === 'datetime'" v-model="params.data[formItm.field]" :type="formItm.compType === 'date' ? 'date' : 'datetime'" placeholder="请输入" clearable></vxe-input>

                <vxe-checkbox-group v-if="formItm.compType === 'checkboxgroup'" v-model="params.data[formItm.field]">
                  <vxe-checkbox :label="itm.label" :content="itm.content" v-for="(itm, idx) in formItm.fieldOptions" :key="idx"></vxe-checkbox>
                </vxe-checkbox-group>
                <vxe-radio-group v-if="formItm.compType === 'radiogroup'" v-model="params.data[formItm.field]">
                  <vxe-radio :label="itm.label" :content="itm.content" v-for="(itm, idx) in formItm.fieldOptions" :key="idx"></vxe-radio>
                </vxe-radio-group>
                <vxe-checkbox v-if="formItm.compType === 'checkbox'" v-model="params.data[formItm.field]" :checked-value="1" :unchecked-value="0"></vxe-checkbox>
                <vxe-input v-if="formItm.compType === 'integer'" v-model="params.data[formItm.field]" type="integer" placeholder="请输入" clearable></vxe-input>
                <vxe-switch v-if="formItm.compType === 'switch'" v-model="params.data[formItm.field]" :open-value="1" :close-value="0" open-label="是" close-label="否"></vxe-switch>
                <vxe-select v-if="formItm.compType === 'select'" v-model="params.data[formItm.field]" placeholder="请选择">
                  <vxe-option v-for="(itm, idx) in formItm.fieldOptions" :key="idx" :value="itm.label" :label="itm.content"></vxe-option>
                </vxe-select>
                <vxe-textarea v-if="formItm.compType === 'textarea'" v-model="params.data[formItm.field]" placeholder="请输入"></vxe-textarea>
              </div>
            </template>
          </vxe-form-item>
          <vxe-form-item>
            <vxe-button content="保存" status="primary" @click="saveGroupFields" class="FormsaveBtn"></vxe-button>
          </vxe-form-item>
        </vxe-form>
      </div>
    </el-tab-pane>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty } from '../utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';
//import ExtraProperties from '@/components/ExtraProperties.vue'; //扩展属性表单组件
let { proxy }: any = getCurrentInstance();
let propsObj = defineProps({
  busRow: {} as any
});

proxy.baseFormData = {} as any;
const formData = reactive({});
const dataStruct = ref([]);
const editableTabsValue = ref(0);

watch(
  () => propsObj.busRow,
  (n, o) => {
    if (proxy.baseFormData) {
      proxy.baseFormData = {} as any;
    }
    if (curTab && !IsEmpty(curTab.value)) {
      const $formRef = proxy.$refs[`formRef${curTab.value.tabKey}`] as any;
      if ($formRef) {
        $formRef[0].reset();
        proxy.$forceUpdate();
      }
    }
    findExtendFieldsValues();
  },
  { deep: true }
);

function findExtenFieldsList() {
  const moduleId = localStorage.getItem('moduleId');
  const menuId = localStorage.getItem('curMenuId');
  dataStruct.length = 0; //放入数据前清空数据
  const url = '/api/sys/sysextenfields/findEditExtenFieldsList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { moduleId: moduleId, menuId: menuId } })
    .then((res: any) => {
      dataStruct.value.length = 0;
      res.data.forEach((e: any) => {
        e.formObj.titleColon = 0;
        e.formData = {} as any;
        dataStruct.value.push(e);
      });
      editableTabsValue.value = 0;
    })
    .catch((err: any) => {
      VxeMessage('获取字典分类列表失败', VxeNotifyType.error);
    });
}
findExtenFieldsList();

/**
 * 表单Item点击事件
 */
function formItemCLick(m, i, data) {
  //todo
}

/**
 * 当前TabPanel点击事件
 */
const curTab = ref({});
function tabPanelClick(item) {
  curTab.value = item;
  findExtendFieldsValues();
}

/**
 * 获取扩展属性 对应值
 */
const extendFieldsValues = reactive({});

function findExtendFieldsValues() {
  if (IsEmpty(curTab.value.tabKey) || IsEmpty(propsObj.busRow.id)) {
    return;
  }
  const moduleId = localStorage.getItem('moduleId');
  const menuId = localStorage.getItem('curMenuId');
  extendFieldsValues.length = 0; //放入数据前清空数据
  const url = '/api/sys/sysextenfieldsvalue/findExtenFieldsValueList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        moduleId: moduleId,
        menuId: menuId,
        tabKey: curTab.value.tabKey,
        busRowId: propsObj.busRow.id
      }
    })
    .then((res: any) => {
      proxy.baseFormData = res.data;
      res.data.columns.forEach((e) => {
        res.data.data.forEach((m) => {
          if (m.fieldCode === e) {
            switch (m.dataType) {
              case 'Integer':
                formData[e] = Number(m.value);
                break;
              case 'Strng':
                formData[e] = m.value;
                break;
              case 'Date':
                formData[e] = m.value;
                break;
              case 'Array<String>':
                formData[e] = JSON.parse(m.value);
                break;
              case 'Array<Integer>':
                formData[e] = JSON.parse(m.value);
                break;
              default:
                formData[e] = '';
                break;
            }
          }
        });
      });
    })
    .catch((err: any) => {
      VxeMessage('获取字典分类列表失败', VxeNotifyType.error);
    });
}

/**
 * 保存该分组属性值
 */
function saveGroupFields() {
  for (const key in formData) {
    if (Object.prototype.hasOwnProperty.call(formData, key)) {
      const v = formData[key];
      proxy.baseFormData.data.forEach((e) => {
        if (key === e.fieldCode) {
          switch (e.dataType) {
            case 'Integer':
            case 'Strng':
            case 'Date':
              e.value = v;
              break;
            case 'Array<String>':
              e.value = JSON.stringify(v);
              break;
            case 'Array<Integer>':
              formData[e] = JSON.parse(m.value);
              e.value = JSON.stringify(v);
              break;
            default:
              e.value = v;
              break;
          }
        }
      });
    }
  }
  const a = 'busRowId';
  proxy.baseFormData[a] = propsObj.busRow.id;

  const url = '/api/sys/sysextenfieldsvalue/saveEditExtenFieldsValueList';
  proxy.$http
    //注意此处的数据条数
    .post(url, proxy.baseFormData)
    .then((res: any) => {
      VxeMessage('保存成功', VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage('获取字典分类列表失败', VxeNotifyType.error);
    });
}

/**单元格样式 */
function cellClassName({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  return 'padding-lr';
}

</script>

<style lang="scss" scoped>
.FormsaveBtn {
  margin: 5px 0 0 80px;
}
:deep(.vxe-button.size--mini.type--button) {
  border-radius: 4px;
}
</style>